<template>
  <t-card :bordered="false">
     <!-- 容器 -->
     <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="searchParams.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
        <t-button
          v-permission="['system:budget-project-name:create']"
          block
          @click="
            handleOpenLeftDialog('create', {
              companyId: searchParams.companyId
            })
          "
        >
          新建项目
        </t-button>
    
        <!-- 类目树 -->
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon
                v-if="!node.data.parentId"
                v-permission="['system:budget-project-name:create']"
                name="add"
                @click="
                  handleOpenLeftDialog('create', {
                    companyId: searchParams.companyId,
                    parentId: node.data.id,
                  })
                "
              />
              <t-icon
                v-permission="['system:budget-project-name:update']"
                name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })"
              />
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDeleteLeft(node.data)"
              >
                <t-icon v-permission="['system:budget-project-name:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.budgetProjectId" class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="3">
            <t-form-item label="项目名称" name="name">
              <t-input v-model:value="params.name" clearable placeholder="" />
            </t-form-item>
          </t-col>
        </custom-search>
        <!-- 自定义表格 -->
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="programmeCRUD.page"
          column-controller-key="ProgrammeList"
          :on-before-set-data="handleTableSetData"
        >
          <template #topContent>
            <div
              style="
                margin-bottom: var(--td-comp-margin-xxl);
              "
            >
              <t-button
                v-permission="['system:budget-project-data:create']"
                @click="
                  handleOpenDialog('create', {
                    companyId: searchParams.companyId,
                    fileUrlList: [],
                    budgetProjectId: searchParams.budgetProjectId,
                    costList:[],
                    costList1:[],
                    costList2:[],
                    costList3:[],
                    quotaList:[]
                  })
                "
              >
                新建项目
              </t-button>
             
            </div>
          </template>
          <template #fileUrl="{ row }">
            <image-viewer :images="[row.fileUrl]" width="80px" height="80px" v-if="row.fileUrl"/>
          </template>
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
          <template #profitMarginTotal="{ row }">
            {{ row.priceTotal!=0.00||0?`${((row.priceTotal-row.costPriceTotal)/row.priceTotal*100).toFixed(2)}%`:'' }}
          </template>
          <template #quotationMainMaterials="{ row }">
            <edit-quotation-dialog 
              :id="row.id" 
              :selling-price="row.quotationMainMaterials" 
              :material-data-type="'1'" 
              @request-success="handleDialogRequestSuccess" 
            />
          </template>
          <template #quotationAssistantMaterials="{ row }">
            <edit-quotation-dialog 
              :id="row.id" 
              :selling-price="row.quotationAssistantMaterials" 
              :material-data-type="'1'" 
              @request-success="handleDialogRequestSuccess" 
            />
          </template>
          <template #quotationArtificial="{ row }">
            <edit-quotation-dialog 
              :id="row.id" 
              :selling-price="row.quotationArtificial" 
              :material-data-type="'1'" 
              @request-success="handleDialogRequestSuccess" 
            />
          </template>
          <template #costMainMaterials="{ row }">
            <cost-dialog 
              :name="row.costMainMaterials" 
              :obj="row" 
              :material-data-type="'1'" 
              v-if="row.costMainMaterials" 
              @request-success="handleDialogRequestSuccess" />
          </template>
          <template #costAssistantMaterials="{ row }">
            <cost-dialog 
              :name="row.costAssistantMaterials" 
              :obj="row" :material-data-type="'2'" 
              v-if="row.costAssistantMaterials" 
              @request-success="handleDialogRequestSuccess" />
          </template>
          <template #costArtificial="{ row }">
            <cost-dialog 
              :name="row.costArtificial" 
              :obj="row" :material-data-type="'3'" 
              v-if="row.costArtificial" 
              @request-success="handleDialogRequestSuccess" />
          </template>
          <template #createTime="{ row }">
            {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template #operation="{ row }">
            <t-space break-line>
              <t-link
                v-permission="['system:budget-project-data:query']"
                theme="primary"
                @click="handleOpenDialog('read', { id: row.id })"
              >
                详情
              </t-link>
              <t-link
                v-permission="['system:budget-project-data:update']"
                theme="primary"
                @click="handleOpenDialog('update', { id: row.id })"
              >
                编辑
              </t-link>
             
              <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
                <t-link v-permission="['system:budget-project-data:delete']" theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!searchParams.budgetProjectId" class="right" title="请先选择项目" style="margin-top: 30vh" />
    </div>
   
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="programmeCRUD"
      header="*项目"
      width="52%"
      :on-before-save-data="handleDialogSaveData"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-row :gutter="[0,24]">
        <t-col :span="6">
          <t-form-item label="项目名称" name="name" :rules="[{ required: true, message: '请输入项目名称' }]">
            <t-input v-model:value="formData.name" placeholder="请输入项目名称" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="单位" name="unit" :rules="[{ required: true, message: '请选择单位' }]">
            <t-select
              v-model:value="formData.unit"
              :options="dictionaryStore.get('unit')"
              placeholder="请选择单位"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.unit = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="材料及工艺说明" name="remark">
            <t-textarea v-model:value="formData.remark" placeholder="请输入材料及工艺说明" :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="图片/视频" name="fileUrl" :rules="[{ required: false, message: '请上传图片/视频' }]">
            <upload 
              v-model:files="formData.fileUrlList" 
              accept="image/*" 
              theme="image" 
              :disabled="readonly"
              @change="
                  (value) => {
                    formData.fileUrl = value[0]?.url;
                  }
                "
              />
          </t-form-item>
        </t-col>
      </t-row>
      <t-form-item label="成本主材" name="costList1" label-align="top">
        <cost-list
          v-model:costList="formData.costList1" 
          :readonly="readonly"
          type="1"
          @update:costList="(val)=>handleCostListChange(val,'sellingPrice1')"/>
      </t-form-item>
      <t-form-item label="售价主材" name="sellingPrice1" :rules="[{ required: true, message: '请输入售价主材' }]">
        <t-input-number :decimal-places="2" v-model:value="formData.sellingPrice1" placeholder="请输入售价主材" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="成本辅材" name="costList2" label-align="top" >
        <cost-list
          v-model:costList="formData.costList2" 
          :readonly="readonly"
          type="2"
          @update:costList="(val)=>handleCostListChange(val,'sellingPrice2')"/>
      </t-form-item>
      <t-form-item label="售价辅材" name="sellingPrice2" :rules="[{ required: false, message: '请输入售价辅材' }]">
        <t-input-number :decimal-places="2" v-model:value="formData.sellingPrice2" placeholder="请输入售价辅材" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="成本人工" name="costList3" label-align="top">
        <cost-list
          v-model:costList="formData.costList3" 
          :readonly="readonly"
          type="3"
          @update:costList="(val)=>handleCostListChange(val,'sellingPrice3')"/>
      </t-form-item>
      <t-form-item label="售价人工" name="sellingPrice3" :rules="[{ required: true, message: '请输入售价人工' }]">
        <t-input-number :decimal-places="2" v-model:value="formData.sellingPrice3" placeholder="请输入售价人工" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
     <!-- 左侧新增材料对话框 -->
     <custom-dialog
      ref="customDialogLeftRef"
      v-slot="{ formData, readonly }"
      :api-map="programmeNameCRUD"
      header="*项目"
      @request-success="handleDialogRequestSuccessLeft"
    >
      <t-form-item label="工程类型" name="name" :rules="[{ required: true, message: '请输入工程类型' }]">
        <t-input v-model:value="formData.name" placeholder="请输入工程类型" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
     
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'BudgetProgramme',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';

import { programmeCRUD, programmeNameCRUD, updateQuotation } from '@/api/budget/programme';
import { getCompanyList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import CostList from './components/CostList.vue';
import CostDialog from './components/CostDialog.vue';
import EditQuotationDialog from './components/EditQuotationDialog.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 搜索参数
const searchParams = reactive({
  companyId: null,
  budgetProjectId: null
});
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    searchParams.companyId = data[0].id;
  });
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '项目名称' },
  { colKey: 'remark', 
    title: '材料及工艺说明', 
    width:160, 
    ellipsis: true,
  },
  { colKey: 'fileUrl', title: '图片/视频' },
  { colKey: 'unit', title: '单位' ,width:60},
  { 
    colKey: 'costPrice', 
    title: '成本(元)',
    children: [
      {colKey:'costMainMaterials', title:'主材',width:75},
      {colKey:'costAssistantMaterials', title:'辅材',width:75},
      {colKey:'costArtificial', title:'人工',width:75},
    ]
   },
  { 
    colKey: 'price', 
    title: '售价(元)',
    children: [
      {colKey:'quotationMainMaterials', title:'主材',width:75},
      {colKey:'quotationAssistantMaterials', title:'辅材',width:75},
      {colKey:'quotationArtificial', title:'人工',width:75},
    ]
   },
  { 
    colKey: 'total', 
    title: '总计',
    children: [
      {colKey:'priceTotal', title:'售价(元)',width:85},
      {colKey:'costPriceTotal', title:'成本价(元)',width:85},
      {colKey:'profitMarginTotal', title:'利润率',width:85},
    ]
  },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 180, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
    companyId: searchParams.companyId,
    budgetProjectId: searchParams.budgetProjectId
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(async () => {
  await handleGetCompanySimpleList();
  handleGetCategory();
});
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  data.list.forEach((row:any)=> {
    if(!row.quotationMainMaterials) row.quotationMainMaterials=0.00
    if(!row.quotationAssistantMaterials) row.quotationAssistantMaterials=0.00
    if(!row.quotationArtificial) row.quotationArtificial=0.00
    row.priceTotal = (row.quotationMainMaterials+row.quotationArtificial+row.quotationAssistantMaterials).toFixed(2)
    row.costPriceTotal = (row.costMainMaterials+row.costAssistantMaterials+row.costArtificial).toFixed(2)
  })
  return data;
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  programmeCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.fileUrlList = [];
  if (params.fileUrl) params.fileUrlList.push({ url: params.fileUrl });
  if(params.costList.length>0) {
    params.costList1=params.costList.filter((item:any)=>item.materialDataType==='1')
    params.costList2=params.costList.filter((item:any)=>item.materialDataType==='2')
    params.costList3=params.costList.filter((item:any)=>item.materialDataType==='3')
  }
  if(params.quotaList.length>0) {
    params.sellingPrice1 = params.quotaList.find((item:any)=>item.materialDataType==='1').sellingPrice
    params.sellingPrice2 = params.quotaList.find((item:any)=>item.materialDataType==='2').sellingPrice
    params.sellingPrice3 = params.quotaList.find((item:any)=>item.materialDataType==='3').sellingPrice
    
    
  }
  
};
// 处理对话框保存数据
const handleDialogSaveData =(params: Record<string, any>)=>{
  console.log(params);
  
  if(params.fileUrlList) {
    delete params.fileUrlList
  }
  params.costList = [...(params.costList1??[]),...(params.costList2??[]),...(params.costList3??[])]
  params.quotaList = [
  { materialDataType: '1', sellingPrice: params.sellingPrice1?params.sellingPrice1:0 },
  { materialDataType: '2', sellingPrice: params.sellingPrice2?params.sellingPrice2:0 },
  { materialDataType: '3', sellingPrice: params.sellingPrice3?params.sellingPrice3:0 },
];


};
// 处理点击类目树
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (node.data.parentId) {
    searchParams.budgetProjectId = node.value;
    handleInitTable();
  }
};
// 自定义材料左侧对话框ref
const customDialogLeftRef = useTemplateRef('customDialogLeftRef');
// 处理打开对话框
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogLeftRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccessLeft = (result: Record<string, any>) => {
  handleGetCategory();
};
// 处理删除左侧
const handleDeleteLeft = (params: Record<string, any>) => {
  if(params.children) {
    MessagePlugin.error('有子节点不允许删除');
  } else {
    programmeNameCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功'); 
      handleGetCategory();
      searchParams.budgetProjectId = null;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
  }
 
};
// 公司change
const handleChangeCompany = () => {
  searchParams.budgetProjectId = null;
  handleGetCategory();
}
// 类目列表
const categoryList = ref([]);
// 类目树
const categoryTree = ref([]);
// 处理获取类目
const handleGetCategory = () => {
  const params = {
    companyId: searchParams.companyId,
    pageSize: -1,
  };
  programmeNameCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};
const handleBlur = (row:any) =>{
  updateQuotation(row).then(res=>{
    MessagePlugin.success('更新成功')
    handleInitTable()
  }).catch(error=>{
    MessagePlugin.error(error)
  })
  if(row.materialDataType==='1') {
    row.isMainClick=false
  } else if(row.materialDataType==='2') {
    row.isAsClick=false
  } else if(row.materialDataType==='3') {
    row.isArClick=false
  }
}


// 监听 costList1 的变化，计算 sellingPrice1
const handleCostListChange = (costList:any,targetField:any) => {
      // formData.value.costList1 = newCostList; // 更新 costList1
      let sellingPrice = 0;
      costList.forEach((item:any) => {
        sellingPrice += item.sellingPrice * item.num;
      });
      customDialogRef.value.formData[targetField] = sellingPrice; // 更新 sellingPrice1
    };


</script>

<style lang="less" scoped>
// 容器
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .left {
    width: 300px;
    height: calc(100vh - 236px);
    overflow: hidden;

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    height: calc(100vh - 236px);
  }

  .right {
    width: calc(100% - 325px);
  }
}
</style>
